from flask import (
    Blueprint,
    request,
    g,
    redirect,
    url_for
)

from exit import db
from decimal import Decimal
from datetime import datetime, date, timedelta
from apps.api.decorators import *
from .forms import *
from .decorators import *
from apps.api.forms import UploadImgForm
from .models import *
from .models_v2 import *
from apps.api.models import *
from apps.common.models import *
from utils import restful, api_util, common_util, deliver_api, api_util_v2
from sqlalchemy import func, or_
import requests
import json
from shortuuid import uuid
from .views_mall import bp


@bp.route('/goods_trade/')  # 转让首页
@login_required_query
def goods_trade():
    page = request.args.get('page', default=1, type=int)
    pages = (page - 1) * 20
    # name = request.args.get('name')
    filters = list()
    filters.append(Goods.status == 1)
    # if name:
    #     filters.append(or_(Goods.name.like('%' + name + '%'), Goods.goods_code.like('%' + name + '%')))
    goods = Goods.query.filter(*filters).order_by(Goods.priority).limit(20).offset(pages)
    goods_list = list()
    for i in goods:
        goods_info = i.goods_json()
        goods_list.append(goods_info)
    index_dict = dict()
    index_dict['goods_list'] = goods_list
    return restful.success(data=index_dict)


@bp.route('/trade_detail/', methods=['POST'])     # 转让详情
@login_required_query
def trade_detail():
    # time_required = api_util.trade_time_required(0)
    # if time_required is False:
    #     return restful.params_error(message='当前时间未开放！')
    form = DetailForm(request.form)

    if form.validate():
        goods_id = form.goods_id.data
        # token = form.token.data
        goods = Goods.query.filter_by(id=goods_id, is_show=0).first()
        # print(goods_id)
        if goods is None:
            return restful.params_error(message='未找到商品,请刷新后重试！')

        user_extend2 = UserExtend2.query.filter_by(user_id=g.user.id, goods_id=goods_id).first()
        if not user_extend2:
            user_extend2 = UserExtend2(goods_id=goods_id, user_id=g.user.id)
            db.session.add(user_extend2)
            db.session.commit()

        goods_info = goods.goods_json()
        goods_info['total_price'] = goods.price * goods.stock_c

        # 服务中心剩余数量
        f_surplus_num = db.session.query(func.sum(HangingOrder.surplus_num)).filter(
            HangingOrder.goods_id == goods_id,
            HangingOrder.r_type == 1,
            HangingOrder.status == 0,
        ).scalar()

        # 供货商剩余数量
        g_surplus_num = db.session.query(func.sum(HangingOrder.surplus_num)).filter(
            HangingOrder.goods_id == goods_id,
            HangingOrder.r_type == 2,
            HangingOrder.status == 0,
        ).scalar()

        goods_info['take_num'] = user_extend2.s_take_num + user_extend2.s_take_num2
        goods_info['take_num2'] = user_extend2.s_take_num2
        goods_info['release_num'] = user_extend2.s_release_num
        goods_info['borrow_num'] = user_extend2.s_borrow_num
        goods_info['sell_num'] = user_extend2.s_sell_num
        goods_info['s_num'] = (user_extend2.s_take_num + user_extend2.s_take_num2 + user_extend2.s_release_num +
                               user_extend2.s_sell_num + user_extend2.s_borrow_num)

        goods_info['f_price'] = goods.price * goods.ratio_f
        goods_info['g_price'] = goods.price * goods.ratio_g
        goods_info['user_status'] = user_extend2.user_status
        goods_info['pp_price'] = 0

        f_surplus_num = f_surplus_num or 0
        g_surplus_num = g_surplus_num or 0
        goods_info['f_surplus_num'] = int(f_surplus_num)
        goods_info['g_surplus_num'] = int(g_surplus_num)
        f_hanging_order_list = api_util_v2.hanging_order_list(goods_id, 1, 1)
        g_hanging_order_list = api_util_v2.hanging_order_list(goods_id, 1, 2)
        goods_info['f_hanging_order_list'] = f_hanging_order_list
        goods_info['g_hanging_order_list'] = g_hanging_order_list

        details = GoodsDetail.query.filter_by(goods_id=goods.id).order_by(GoodsDetail.priority).all()
        banner_list = list()
        detail_list = list()

        for i in details:
            detail_json = i.goods_detail_json()
            if i.status == 0:
                banner_list.append(detail_json)
            else:
                detail_list.append(detail_json)
        goods_info['banner_list'] = banner_list
        goods_info['detail_list'] = detail_list

        increase = goods.increase_num_now / goods.increase_num
        if increase >= 0.9:
            return restful.success(data=goods_info, message='商品即将涨价！')
        return restful.success(data=goods_info)
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/trade_goods_detail/')     # 转让商品买卖详情
@login_required_query
def trade_goods_detail():
    goods_id = request.args.get('goods_id')
    goods = Goods.query.filter_by(id=goods_id, status=1).first()
    if goods is None:
        return restful.params_error("未找到该商品")

    user_extend2 = UserExtend2.query.filter_by(user_id=g.user.id, goods_id=goods_id).first()
    if user_extend2 is None:
        user_extend2 = UserExtend2(user_id=g.user.id, goods_id=goods_id)
        db.session.add(user_extend2)
        db.session.commit()

    result = dict()
    result["goods_dict"] = goods.goods_json()
    result["user_dict"] = user_extend2.user_extend2_json()

    return restful.success(data=result)


@bp.route('/trade_goods_buy_yj/', methods=['POST'])     # 转让商品原价买
@login_required_query
def trade_goods_buy_yj():
    goods_id = request.form.get('goods_id')
    goods_price = Decimal(str(request.form.get('goods_price', type=float)))
    num = request.form.get('num', type=int)

    if num <= 0:
        return restful.params_error("请输入正确的购买数量")

    goods = Goods.query.filter_by(id=goods_id, status=1).first()
    if goods is None:
        return restful.params_error("未找到该商品")
    if goods.goods_status == 2:
        return restful.params_error("商品涨价中")
    if goods.price != goods_price:
        return restful.params_error("商品价格已失效")

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods_id)

    total_price = goods.price * num
    buy_fee = total_price * goods.fees
    if g.user.income < total_price + buy_fee:
        return restful.params_error("用户余额不足")

    # 锁goods表
    goods = Goods.query.filter_by(id=goods_id, status=1).with_for_update().first()
    if goods.goods_status == 2:
        return restful.params_error("商品涨价中")
    if goods.price != goods_price:
        return restful.params_error("商品价格已失效")

    goods.stock_c -= num
    goods.add_increase_num(num)

    # 插入trade表
    if user_extend2.user_status == 0:
        # 插入trade表
        trade_record = MallTrade(buyer_id=g.user.id, buyer_status=user_extend2.user_status, deal_num=num,
                                 goods_id=goods.id, deal_price=goods.price, deal_money=total_price,
                                 buy_fee=buy_fee, goods_cycle=goods.cycle, deal_type=3, buy_type=1)
        db.session.add(trade_record)
        db.session.flush()

        # 添加批次
        batch_record = MallBatch(order_id=trade_record.id, goods_id=goods.id, user_id=g.user.id, deal_num=num, buy_type=1,
                                 t_take_num=num, s_num_take=num)
        db.session.add(batch_record)

        # 做记录
        user_extend2.s_take_num += num
        api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)
        g.user.income -= total_price + buy_fee
        api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)

    else:
        # 插入trade表
        trade_record = MallTrade(buyer_id=g.user.id, buyer_status=user_extend2.user_status, deal_num=num,
                                 goods_id=goods.id, deal_price=goods.price, deal_money=total_price,
                                 buy_fee=buy_fee, goods_cycle=goods.cycle, deal_type=3, buy_type=1)

        db.session.add(trade_record)
        db.session.flush()

        # 添加批次
        batch_record = MallBatch(order_id=trade_record.id, goods_id=goods.id, user_id=g.user.id, deal_num=num, buy_type=1,
                                 t_sell_num=num, s_num_sell=num)
        db.session.add(batch_record)

        # 做记录
        user_extend2.s_sell_num += num
        api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)
        g.user.income -= total_price + buy_fee
        api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)

    db.session.commit()
    return restful.success(message="购买成功")


@bp.route('/trade_goods_buy_tj/', methods=['POST'])  # 转让商品买特价
@login_required_query
def trade_goods_buy_tj():
    goods_id = request.form.get('goods_id')
    goods_price = Decimal(str(request.form.get('goods_price', type=float)))
    num = request.form.get('num', type=int)

    if num <= 0:
        return restful.params_error("请输入正确的购买数量")
    if num % 2 > 0:
        return restful.params_error("只能购买2的倍数")

    goods = Goods.query.filter_by(id=goods_id, status=1).first()
    if goods is None:
        return restful.params_error("未找到该商品")
    if goods.goods_status == 2:
        return restful.params_error("商品涨价中")
    if goods.old_price != goods_price:
        return restful.params_error("商品价格已失效")

    total_price = goods.old_price * num
    buy_fee = total_price * goods.fees
    if g.user.income < total_price + buy_fee:
        return restful.params_error("用户余额不足")

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods_id)

    if user_extend2.user_status != 0:
        return restful.params_error("非普通用户无法购买特价商品")

    if user_extend2.s_coupon_num < num:
        return restful.params_error("特价券不足")

    # 锁goods表
    goods = Goods.query.filter_by(id=goods_id, status=1).with_for_update().first()
    if goods.goods_status == 2:
        return restful.params_error("商品涨价中")
    if goods.old_price != goods_price:
        return restful.params_error("商品价格已失效")

    goods.stock_c -= num

    # 插入trade表
    trade_record = MallTrade(buyer_id=g.user.id, buyer_status=user_extend2.user_status, deal_num=num,
                             goods_id=goods.id, deal_price=goods.old_price, deal_money=total_price,
                             buy_fee=buy_fee, goods_cycle=goods.cycle, deal_type=3, buy_type=3)

    db.session.add(trade_record)
    db.session.flush()

    # 添加批次
    batch_record = MallBatch(order_id=trade_record.id, goods_id=goods.id, user_id=g.user.id, deal_num=num, buy_type=3,
                             t_borrow_num=num/2, t_release_num=num/2, s_num_borrow=num/2, s_num_release=num/2)
    db.session.add(batch_record)

    # 做记录
    user_extend2.s_coupon_num -= num
    api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)
    # 循环扣优惠券
    # deduct_num = num
    # coupon_list = MallCoupon.query.fitler_by(user_id=g.user.id, goods_id=goods_id, status=0, t_type=1).order_by(MallCoupon.create_time).all()
    # for i in coupon_list:
    #     if deduct_num <= i.s_num:
    #         i.s_num -= deduct_num
    #         break
    #     else:
    #         deduct_num -= i.s_num
    #         i.s_num = 0

    user_extend2.s_borrow_num += num / 2
    api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)
    user_extend2.s_release_num += num / 2
    api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)

    g.user.income -= total_price + buy_fee
    api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)

    db.session.commit()
    return restful.success(message="购买成功")


@bp.route('/trade_goods_buy_yh/', methods=['POST'])  # 转让商品买优惠
@login_required_query
def trade_goods_buy_yh():
    goods_id = request.form.get('goods_id')
    goods_price = Decimal(str(request.form.get('goods_price', type=float)))
    num = request.form.get('num', type=int)

    if num <= 0:
        return restful.params_error("请输入正确的购买数量")

    goods = Goods.query.filter_by(id=goods_id, status=1).first()
    if goods is None:
        return restful.params_error("未找到该商品")
    if goods.goods_status == 2:
        return restful.params_error("商品涨价中")
    if goods.old_price != goods_price:
        return restful.params_error("商品价格已失效")

    total_price = goods.old_price * num
    buy_fee = total_price * goods.fees
    if g.user.income < total_price + buy_fee:
        return restful.params_error("用户余额不足")

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods_id)

    if user_extend2.user_status != 0:
        return restful.params_error("非普通用户无法购买特价商品")

    if user_extend2.s_discount_num < num:
        return restful.params_error("优惠券不足")

    # 锁goods表
    goods = Goods.query.filter_by(id=goods_id, status=1).with_for_update().first()
    if goods.goods_status == 2:
        return restful.params_error("商品涨价中")
    if goods.old_price != goods_price:
        return restful.params_error("商品价格已失效")

    goods.stock_c -= num

    # 插入trade表
    trade_record = MallTrade(buyer_id=g.user.id, buyer_status=user_extend2.user_status, deal_num=num,
                             goods_id=goods.id, deal_price=goods.old_price, deal_money=total_price,
                             buy_fee=buy_fee, goods_cycle=goods.cycle, deal_type=3, buy_type=4)

    db.session.add(trade_record)
    db.session.flush()

    # 添加批次
    batch_record = MallBatch(order_id=trade_record.id, goods_id=goods.id, user_id=g.user.id, deal_num=num, buy_type=4,
                             t_release_num=num, s_num_release=num)
    db.session.add(batch_record)

    # 做记录
    user_extend2.s_discount_num -= num
    api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)
    # 循环扣特价券
    # deduct_num = num
    # coupon_list = MallCoupon.query.fitler_by(user_id=g.user.id, goods_id=goods_id, status=0, t_type=2).order_by(MallCoupon.create_time).all()
    # for i in coupon_list:
    #     if deduct_num <= i.s_num:
    #         i.s_num -= deduct_num
    #         break
    #     else:
    #         deduct_num -= i.s_num
    #         i.s_num = 0

    user_extend2.s_release_num += num
    api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)

    g.user.income -= total_price + buy_fee
    api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fee, order_id=trade_record.id)

    db.session.commit()
    return restful.success(message="购买成功")


@bp.route('/hang_order/', methods=['POST'])      # 挂单
@login_required_query
def hang_order():
    time_required = api_util.trade_time_required(6)
    time_required2 = api_util.trade_time_required(7)
    if time_required is False and time_required2 is False:
        return restful.params_error(message='当前时间未开放！')

    # 挂卖只能普通用户，需要数量、类型
    goods_id = request.form.get('goods_id')
    num = request.form.get('num', type=int)
    r_type = request.form.get('r_type', type=int)
    goods_price = Decimal(str(request.form.get('goods_price', type=float)))

    if r_type not in (1, 2):
        return restful.params_error('参数不正确')

    goods = Goods.query.filter_by(id=goods_id, status=1).first()
    if not goods:
        return restful.params_error('未找到该商品')
    elif goods.goods_status == 1:
        return restful.params_error('商品暂停交易')
    elif goods.goods_status == 2:
        return restful.params_error('商品涨价中')
    elif goods.price != goods_price:
        return restful.params_error('商品价格已失效')

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods_id)

    if user_extend2.user_status != 0:
        return restful.params_error('权限不足，无法挂卖')

    try:
        if user_extend2.s_sell_num < num:
            return restful.params_error('可卖数量不足')

        # 这里加了一个读锁，因为必须保证这个单子成功上架，不锁的话，可能上架到下一个价格了
        goods = Goods.query.filter_by(id=goods_id, status=1).with_for_update(read=True).first()
        if goods.goods_status != 0:
            return restful.params_error('商品涨价中')
        elif goods.price != goods_price:
            return restful.params_error('商品价格已失效')

        if r_type == 1:     # r_type 1服务中心  2供应商
            order_price = goods.price * goods.ratio_f
        else:
            order_price = goods.price * goods.ratio_g

        # 扣除数量
        user_extend2.s_sell_num -= num
        # 生成挂单
        record = HangingOrder(
            user_id=g.user.id, user_status=0, status=0, goods_id=goods_id, price=order_price, total_num=num,
            r_type=r_type, surplus_num=num, price_yj=goods.price, goods_cycle=goods.cycle
        )
        db.session.add(record)
        db.session.commit()
        return restful.success()
    except Exception as e:
        print(e)
        db.session.rollback()
        return restful.params_error('网络繁忙，请重试')


@bp.route('/pick_order/', methods=['POST'])     # 摘单
@login_required
def pick_order():
    time_required = api_util.trade_time_required(6)
    time_required2 = api_util.trade_time_required(7)
    if time_required is False and time_required2 is False:
        return restful.params_error(message='当前时间未开放！')

    # 摘单只能是服务中心和供应商
    order_id = request.form.get('order_id', type=int)
    num = request.form.get('num', type=int)

    if num <= 0:
        return restful.params_error('请填写正确的数量')

    order = HangingOrder.query.filter_by(id=order_id, status=0).first()
    if not order:
        return restful.params_error('未找到订单')
    elif order.surplus_num < num:
        return restful.params_error('订单数量不足')
    elif order.user_id == g.user.id:
        return restful.params_error('不能和自己成交')

    goods = Goods.query.filter_by(id=order.goods_id, status=1).first()
    if goods is None:
        return restful.params_error('未找到该商品')
    elif goods.goods_status == 1:
        return restful.params_error('商品暂停交易')
    elif goods.goods_status == 2:
        return restful.params_error('商品涨价中')

    total_price = num * order.price
    sell_fees = total_price * goods.fees
    buy_fees = total_price * goods.fees

    if g.user.income < total_price + buy_fees:
        return restful.params_error('用户资产不足')

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, order.goods_id)

    if user_extend2.user_status != order.r_type:
        return restful.params_error('权限不足，无法购买')

    # 锁订单、锁卖家、锁买家
    try:
        sell_user = User.query.filter_by(id=order.user_id).with_for_update().first()
        order = HangingOrder.query.filter_by(id=order.id, status=0).with_for_update().first()
        if order is None:
            return restful.params_error('订单已失效')
        elif order.surplus_num < num:
            return restful.params_error('订单数量不足')

        goods = Goods.query.filter_by(id=goods.id, status=1).with_for_update(read=True).first()
        if goods.goods_status == 1:
            return restful.params_error('商品暂停交易')
        elif goods.goods_status == 2:
            return restful.params_error('商品涨价中')

        # 1.扣数量，给卖家钱，做记录
        order.surplus_num -= num
        if order.surplus_num == 0:
            order.status = 1

        # 3.生成订单，创建批次
        trade_record = MallTrade(
            buy_order_id=order_id, buyer_id=g.user.id, buyer_status=user_extend2.user_status, seller_id=sell_user.id,
            seller_status=0, deal_num=num, deal_price=goods.price, deal_money=total_price, goods_id=goods.id,
            buy_fee=buy_fees, sell_fee=sell_fees, goods_cycle=goods.cycle, deal_type=2, buy_type=2, sell_type=1,
            is_main=1, main_num=num
        )

        db.session.add(trade_record)
        db.session.flush()

        # 添加批次
        batch_record = MallBatch(order_id=trade_record.id, goods_id=goods.id, user_id=g.user.id, deal_num=num,
                                 buy_type=2, t_sell_num=num, s_num_sell=num)
        db.session.add(batch_record)

        # 做记录
        sell_user.income += total_price - sell_fees
        api_util.user_record(sell_user.id, r_label=3, r_type=21, r_state=1, r_wallet=1, num=total_price, order_id=order_id)
        api_util.user_record(sell_user.id, r_label=2, r_type=22, r_state=1, r_wallet=1, num=sell_fees, order_id=order_id)

        # 2.扣用户的钱，还有特价券，做记录
        g.user.income -= total_price + buy_fees
        api_util.user_record(g.user.id, r_label=1, r_type=21, r_state=2, r_wallet=1, num=total_price, order_id=order_id)
        api_util.user_record(g.user.id, r_label=2, r_type=21, r_state=2, r_wallet=1, num=buy_fees, order_id=order_id)

        user_extend2.s_sell_num += num
        api_util.user_record(g.user.id, 1, 1, 2, 1, total_price + buy_fees, order_id=trade_record.id)
        # 卖家循环扣batch表
        # deduct_num = num
        # batch_list = MallBatch.query.filter(MallBatch.user_id == g.user.id, MallBatch.goods_id == order.goods_id,
        #                                     MallBatch.s_num_sell > 0).order_by(MallBatch.create_time).all()
        # for i in batch_list:
        #     if deduct_num <= i.s_num_sell:
        #         i.s_num_sell -= deduct_num
        #         break
        #     else:
        #         deduct_num -= i.s_num_sell
        #         i.s_num_sell = 0

        db.session.commit()
        return restful.success()

    except Exception as e:
        print(e)
        db.session.rollback()
        db.session.close()
        return restful.params_error('网络繁忙，请重试')


@bp.route('/hanging_order_record/')     # 我的挂单
@login_required_query
def hanging_order_record():
    page = request.args.get('page', type=int, default=1)
    page_limit = request.args.get('page', type=int, default=20)
    goods_id = request.args.get('goods_id')
    status = request.args.get('status', type=int)   # 0正常  1已成交

    pages = (page - 1) * page_limit

    filters = list()
    filters.append(HangingOrder.goods_id == goods_id)
    filters.append(HangingOrder.user_id == g.user.id)

    if status == 0:
        filters.append(HangingOrder.status == 0)
    elif status == 1:
        filters.append(HangingOrder.status != 0)

    hanging_order = HangingOrder.query.filter(*filters).order_by(HangingOrder.create_time.desc()).limit(page_limit).offset(pages)
    record_list = list()
    for i in hanging_order:
        record_info = i.hanging_order_json()
        record_list.append(record_info)

    data_dict = dict()
    data_dict['order_list'] = record_list
    return restful.success(data=data_dict)


@bp.route('/hanging_order_hall/')     # 挂单大厅
@login_required_query
def hanging_order_hall():
    page = request.args.get('page', type=int, default=1)
    page_limit = request.args.get('page_limit', type=int, default=20)
    pages = (page - 1) * page_limit
    goods_id = request.args.get('goods_id')

    goods = Goods.query.filter_by(id=goods_id, status=1).first()
    if goods is None:
        return restful.params_error("未找到该商品")
    elif goods.goods_status == 1:
        return restful.params_error("商品暂停交易")
    elif goods.goods_status == 2:
        return restful.params_error("商品涨价中")

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods_id=goods_id)

    hanging_order = HangingOrder.query.filter_by(goods_id=goods_id, status=0, r_type=user_extend2.user_status).order_by(HangingOrder.create_time.desc()).limit(page_limit).offset(pages)
    record_list = list()
    for i in hanging_order:
        record_info = i.hanging_order_json()
        user = User.query.filter_by(id=i.user_id).first()
        if user:
            record_info['phone'] = user.phone[0:3] + '********'
        record_list.append(record_info)

    data_dict = dict()
    data_dict['order_list'] = record_list
    return restful.success(data=data_dict)


@bp.route('/revoke_hang_order/', methods=['POST'])      # 撤回挂单
@login_required_query
def revoke_hang_order():
    order_id = request.form.get('order_id')

    try:
        order = HangingOrder.query.filter_by(id=order_id, user_id=g.user.id).with_for_update().first()
        if order is None:
            return restful.params_error('未找到订单')
        if order.status != 0:
            return restful.params_error('订单已失效')

        user_extend2 = UserExtend2.query.filter_by(user_id=g.user.id, goods_id=order.goods_id).with_for_update().first()
        user_extend2.s_sell_num += order.surplus_num

        order.status = 2
        order.update_time = datetime.now()
        db.session.commit()
        return restful.success()

    except Exception as e:
        print(e)
        db.session.rollback()
        return restful.params_error('网络繁忙，请重试')


@bp.route('/borrow_transfer/', methods=['POST'])      # 预支点对点
@login_required_query
def borrow_transfer():
    if g.user.status != 2:
        return restful.params_error(message='未实名不能交易')
    # time_required = api_util.trade_time_required(6)
    # time_required2 = api_util.trade_time_required(7)
    # if time_required is False and time_required2 is False:
    #     return restful.params_error(message='当前时间未开放！')

    phone = request.form.get('phone')
    goods_id = request.form.get('goods_id')
    num = request.form.get('num', type=int)
    goods_price = Decimal(str(request.form.get('goods_price', type=float)))

    if num <= 0:
        return restful.params_error(message="请输入正确的数量")
    if num % 2 != 0:
        return restful.params_error(message="只能卖出2的倍数的数量")
    if phone == g.user.phone:
        return restful.params_error(message='不能转给自己')

    goods = Goods.query.filter_by(id=goods_id, status=1).first()
    if goods is None:
        return restful.params_error(message='未找到商品')
    elif goods.goods_status == 1:
        return restful.params_error('商品暂停交易')
    elif goods.goods_status == 2:
        return restful.params_error('商品涨价中')
    elif goods.price != goods_price:
        print(goods_price, goods.price)
        return restful.params_error(message="商品价格已失效")

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods_id)
    if user_extend2.s_borrow_num < num:
        return restful.params_error(message="预支票数量不足")

    other_user = User.query.filter_by(phone=phone).first()
    if other_user is None:
        return restful.params_error(message='未找到用户')

    # 锁goods表
    try:
        goods = Goods.query.filter_by(id=goods_id, status=1).with_for_update(read=True).first()
        if goods.goods_status == 1:
            return restful.params_error('商品暂停交易')
        elif goods.goods_status == 2:
            return restful.params_error('商品涨价中')
        elif goods.price != goods_price:
            return restful.params_error(message="商品价格已失效")

        # 扣除预支数量
        user_extend2.s_borrow_num -= num
        api_util.user_record(g.user.id, 10, 1, 2, 1, num)

        create_transfer = MallTransferOrder(
            user_id=g.user.id, to_user_id=other_user.id, goods_id=goods_id, goods_cycle=goods.cycle, status=0,
            num_ys=num, num=num*2, price=goods.price, total_money=goods.price * num * 2,  deal_type=1, sell_type=2,
            user_status=user_extend2.user_status
        )
        db.session.add(create_transfer)
        db.session.commit()
        return restful.success(message='成功')
    except Exception as e:
        print(e)
        db.session.rollback()
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


@bp.route('/seller_transfer_batch/', methods=['POST'])      # 普通点对点
@login_required_query
def seller_transfer_batch():
    if g.user.status != 2:
        return restful.params_error(message='未实名不能交易')
    # time_required = api_util.trade_time_required(6)
    # time_required2 = api_util.trade_time_required(7)
    # if time_required is False and time_required2 is False:
    #     return restful.params_error(message='当前时间未开放！')

    try:

        phone = request.form.get('phone')
        goods_id = request.form.get('goods_id')
        num = request.form.get('num', type=int)
        goods_price = Decimal(str(request.form.get('goods_price', type=float)))

        if num <= 0:
            return restful.params_error(message="请输入正确的数量")
        if phone == g.user.phone:
            return restful.params_error(message='不能转给自己')

        goods = Goods.query.filter_by(id=goods_id, status=1).first()
        if goods is None:
            return restful.params_error(message='未找到商品')
        elif goods.goods_status == 1:
            return restful.params_error('商品暂停交易')
        elif goods.goods_status == 2:
            return restful.params_error('商品涨价中')
        elif goods.price != goods_price:
            print(goods_price, goods.price)
            return restful.params_error(message="商品价格已失效")

        user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods_id)
        if user_extend2.s_sell_num < num:
            return restful.params_error(message="可卖票数量不足")

        other_user = User.query.filter_by(phone=phone).first()
        if other_user is None:
            return restful.params_error(message='未找到用户')

        # 锁goods表
        goods = Goods.query.filter_by(id=goods_id, status=1).with_for_update(read=True).first()
        if goods.goods_status == 1:
            return restful.params_error('商品暂停交易')
        elif goods.goods_status == 2:
            return restful.params_error('商品涨价中')
        elif goods.price != goods_price:
            return restful.params_error(message="商品价格已失效")

        # 扣除预支数量
        user_extend2.s_sell_num -= num
        api_util.user_record(g.user.id, 10, 1, 2, 1, num)

        create_transfer = MallTransferOrder(
            user_id=g.user.id, to_user_id=other_user.id, goods_id=goods_id, goods_cycle=goods.cycle, status=0,
            num_ys=num, num=num, price=goods.price, total_money=goods.price * num, deal_type=1, sell_type=1,
            user_status=user_extend2.user_status
        )
        db.session.add(create_transfer)
        db.session.commit()
        return restful.success(message='成功')
    except Exception as e:
        print(e)
        db.session.rollback()
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


# 点对点列表 转给别人的，别人转给自己的 明细
@bp.route('/transfer_order_record_v2/', methods=['POST'])     # 转让记录
@login_required_query
def transfer_order_record_v2():
    page = request.form.get('page', type=int, default=1)
    page_limit = request.form.get('page_limit', type=int, default=20)
    t_type = request.form.get('t_type', type=int)   # 0已完成的， 1转给别人的，2别人转给自己的

    pages = (page - 1) * 20

    filters = list()

    if t_type == 0:
        filters.append(or_(MallTransferOrder.user_id == g.user.id, MallTransferOrder.to_user_id == g.user.id))
        filters.append(MallTransferOrder.status != 0)
    if t_type == 1:
        filters.append(MallTransferOrder.user_id == g.user.id)
        filters.append(MallTransferOrder.status == 0)
    else:
        filters.append(MallTransferOrder.to_user_id == g.user.id)
        filters.append(MallTransferOrder.status == 0)

    transfer_order = MallTransferOrder.query.filter(*filters).order_by(MallTransferOrder.create_time.desc()).limit(
            page_limit).offset(pages)
    order_list = list()

    for i in transfer_order:
        order_json = i.transfer_order_json()
        order_json['order_id'] = i.id
        order_json['num'] = Decimal(i.num)
        seller = User.query.filter_by(id=i.user_id).first()
        buyer = User.query.filter_by(id=i.to_user_id).first()
        order_json['seller_name'] = seller.real_name
        order_json['seller_phone'] = seller.phone
        order_json['buyer_name'] = buyer.real_name
        order_json['buyer_phone'] = buyer.phone
        # goods_list = list()
        goods = Goods.query.filter_by(id=i.goods_id).first()
        if goods:
            order_json['name'] = goods.name
            order_json['goods_code'] = goods.goods_code
        if i.user_id == g.user.id:
            order_json['status_str'] = '点对点转出'
        else:
            order_json['status_str'] = '点对点转入'
        order_list.append(order_json)

    order_dict = dict()
    order_dict['order_list'] = order_list
    return restful.success(data=order_dict)


@bp.route('/fail_transfer_order/', methods=['POST'])  # 撤回点对点
@login_required_query
def fail_transfer_order():
    # time_required = api_util.trade_time_required(6)
    # time_required2 = api_util.trade_time_required(7)
    # if time_required is False and time_required2 is False:
    #     return restful.params_error(message='当前时间未开放！')

    order_id = request.form.get('order_id')
    transfer_order = MallTransferOrder.query.filter_by(id=order_id, user_id=g.user.id, status=0).with_for_update().first()
    if transfer_order is None:
        return restful.params_error(message='未找到订单')

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, transfer_order.goods_id)

    if transfer_order.sell_type == 1:
        user_extend2.s_sell_num += transfer_order.num_ys
        api_util.user_record(g.user.id, 1, 1, 1, 1, transfer_order.num_ys, order_id=transfer_order.id)
    elif transfer_order.sell_type == 2:
        user_extend2.s_borrow_num += transfer_order.num_ys
        api_util.user_record(g.user.id, 1, 1, 1, 1, transfer_order.num_ys, order_id=transfer_order.id)

    transfer_order.status = 2
    transfer_order.update_time = datetime.now()

    db.session.commit()
    return restful.success(message='撤单成功')


@bp.route('/confirm_buyer/', methods=['POST'])      # 确认点对点
@login_required
def confirm_buyer():
    time_required = api_util.trade_time_required(6)
    time_required2 = api_util.trade_time_required(7)
    if time_required is False and time_required2 is False:
        return restful.params_error(message='当前时间未开放！')

    order_id = request.form.get('order_id')

    order = MallTransferOrder.query.filter_by(id=order_id, to_user_id=g.user.id, status=0).first()
    if order is None:
        return restful.params_error(message='未找到订单')

    goods = Goods.query.filter_by(id=order.goods_id, status=1).first()
    if goods.goods_status == 1:
        return restful.params_error(message='商品暂停交易')
    elif goods.goods_status == 2:
        return restful.params_error(message='商品涨价中')

    buy_total_price = order.num * order.price           # 买家需付款
    buy_fee = buy_total_price * goods.fees              # 买家手续费
    sell_total_price = order.num_ys * order.price   # 卖家收款金额
    sell_fee = sell_total_price * goods.fees        # 卖家手续费

    if g.user.income < buy_total_price + buy_fee:
        return restful.params_error("可用资金不足")

    try:
        order = MallTransferOrder.query.filter_by(id=order_id).with_for_update().first()
        if order.status != 0:
            return restful.params_error("订单已失效")

        user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods.id)
        seller = User.query.filter_by(id=order.user_id).with_for_update().first()

        goods = Goods.query.filter_by(id=goods.id).with_for_update().first()
        if goods.goods_status == 1:
            return restful.params_error('商品暂停交易')
        elif goods.goods_status == 2:
            return restful.params_error('商品涨价中')

        # 普通用户插入trade表
        trade_record = MallTrade(
            transfer_order_id=order.id, seller_id=order.user_id, seller_status=order.user_status,
            buyer_id=g.user.id, buyer_status=user_extend2.user_status, goods_id=goods.id, goods_cycle=goods.cycle,
            deal_num=order.num_ys, deal_price=goods.price, deal_money=order.num_ys * goods.price, buy_fee=buy_fee,
            sell_fee=sell_fee, deal_type=3, buy_type=1, is_main=1, main_num=order.num, sell_type=order.sell_type
        )
        db.session.add(trade_record)
        db.session.flush()

        # 添加批次
        if user_extend2.user_status == 0:       # 普通用户
            # 添加批次
            batch_record = MallBatch(
                order_id=trade_record.id, goods_id=goods.id, user_id=g.user.id, deal_num=order.num,
                buy_type=1, t_take_num=order.num, s_num_take=order.num
            )
            db.session.add(batch_record)

            # 加数量，做记录
            user_extend2.s_take_num += order.num
            api_util.user_record(g.user.id, 1, 1, 2, 1, order.num, order_id=trade_record.id)

        else:
            batch_record = MallBatch(
                order_id=trade_record.id, goods_id=goods.id, user_id=g.user.id, deal_num=order.num,
                buy_type=1, t_sell_num=order.num, s_num_sell=order.num
            )
            db.session.add(batch_record)

            # 做记录
            user_extend2.s_sell_num += order.num
            api_util.user_record(g.user.id, 1, 1, 2, 1, order.num, order_id=trade_record.id)

        # 如果是预支点对点，需要带票
        if order.sell_type == 2:
            # 找到上家
            fw_user = None      # 服务中心用户
            gy_user = None      # 供应商用户
            max_level = 0
            p_user = User.query.filter_by(id=g.user.p_id).first()
            while p_user:
                p_user_extend2 = UserExtend2.query.filter_by(user_id=p_user.id, goods_id=order.goods_id).first()
                if p_user_extend2 and p_user_extend2.user_status > max_level:

                    if p_user_extend2.user_status == 1:
                        max_level = 1
                        if p_user_extend2.s_sell_num > order.num_ys / 2:
                            fw_user = p_user
                    else:
                        gy_user = p_user
                p_user = User.query.filter_by(id=p_user.p_id).first()

            if gy_user is None:
                return restful.params_error("未找到供应商")

            fw_user = User.query.filter_by(id=fw_user.id).with_for_update().first()
            fw_user_extend2 = UserExtend2.query.filter_by(user_id=fw_user.id, goods_id=order.goods_id).with_for_update().first()
            if fw_user_extend2.s_sell_num < order.num_ys:
                fw_user = None

            # 供应商必须有
            gy_user = User.query.filter_by(id=fw_user.id).with_for_update().first()
            gy_user_extend2 = UserExtend2.query.filter_by(user_id=gy_user.id, goods_id=order.goods_id).with_for_update().first()

            # 带票
            if fw_user and gy_user:     # 服务中心和供应商都存在
                # 服务中心
                trade_record1 = MallTrade(
                    transfer_order_id=order.id, seller_id=fw_user.id, seller_status=fw_user_extend2.user_status,
                    buyer_id=g.user.id, buyer_status=user_extend2.user_status, goods_id=goods.id,
                    goods_cycle=goods.cycle, deal_num=order.num_ys, deal_price=goods.price,
                    deal_money=order.num_ys * goods.price, buy_fee=buy_fee, sell_fee=sell_fee, deal_type=3,
                    buy_type=1, is_main=0, main_num=order.num, sell_type=order.sell_type
                )
                db.session.add(trade_record1)

                # 服务中心加钱做记录
                fw_price = 90
                fw_fees = 9
                fw_user_extend2.s_sell_num -= order.num_ys
                api_util.user_record(g.user.id, 1, 1, 2, 1, order.num, order_id=trade_record.id)

                fw_user.income += fw_price - fw_fees
                api_util.user_record(g.user.id, 1, 1, 2, 1, buy_total_price, order_id=trade_record.id)  # 买货款
                api_util.user_record(g.user.id, 1, 1, 2, 1, buy_fee, order_id=trade_record.id)  # 买手续费

                # 供应商
                trade_record2 = MallTrade(
                    transfer_order_id=order.id, seller_id=order.user_id, seller_status=order.user_status,
                    buyer_id=g.user.id, buyer_status=user_extend2.user_status, goods_id=goods.id,
                    goods_cycle=goods.cycle, deal_num=order.num_ys, deal_price=goods.price,
                    deal_money=order.num_ys * goods.price, buy_fee=buy_fee, sell_fee=sell_fee, deal_type=3,
                    buy_type=1, is_main=0, main_num=order.num, sell_type=order.sell_type
                )
                db.session.add(trade_record2)

                # 供应商加钱做记录
                fw_price = 90
                fw_fees = 9
                fw_user_extend2.s_sell_num -= order.num_ys
                api_util.user_record(g.user.id, 1, 1, 2, 1, order.num, order_id=trade_record.id)

                fw_user.income += fw_price - fw_fees
                api_util.user_record(g.user.id, 1, 1, 2, 1, buy_total_price, order_id=trade_record.id)  # 买货款
                api_util.user_record(g.user.id, 1, 1, 2, 1, buy_fee, order_id=trade_record.id)  # 买手续费
                # todo 循环扣除

            else:       # 服务中心不存在，供应商存在

                trade_record2 = MallTrade(
                    transfer_order_id=order.id, seller_id=order.user_id, seller_status=order.user_status,
                    buyer_id=g.user.id, buyer_status=user_extend2.user_status, goods_id=goods.id,
                    goods_cycle=goods.cycle, deal_num=order.num_ys, deal_price=goods.price,
                    deal_money=order.num_ys * goods.price, buy_fee=buy_fee, sell_fee=sell_fee, deal_type=3,
                    buy_type=1, is_main=0, main_num=order.num, sell_type=order.sell_type
                )
                db.session.add(trade_record2)

                # 供应商加钱做记录
                fw_price = 90
                fw_fees = 9
                fw_user_extend2.s_sell_num -= order.num_ys
                api_util.user_record(g.user.id, 1, 1, 2, 1, order.num, order_id=trade_record.id)

                fw_user.income += fw_price - fw_fees
                api_util.user_record(g.user.id, 1, 1, 2, 1, buy_total_price, order_id=trade_record.id)  # 买货款
                api_util.user_record(g.user.id, 1, 1, 2, 1, buy_fee, order_id=trade_record.id)  # 买手续费
                # todo 循环扣除

        # 买家扣钱
        g.user.income -= buy_total_price + buy_fee
        api_util.user_record(g.user.id, 1, 1, 2, 1, buy_total_price, order_id=trade_record.id)  # 买货款
        api_util.user_record(g.user.id, 1, 1, 2, 1, buy_fee, order_id=trade_record.id)  # 买手续费

        # 卖家加钱
        seller.income += sell_total_price - sell_fee
        api_util.user_record(seller.id, 1, 1, 20, 1, sell_total_price, order_id=order.id)  # 卖出的钱
        api_util.user_record(seller.id, 1, 1, 20, 2, sell_fee, order_id=order.id)  # 手续费
        # todo 循环扣除

        # 更改订单状态
        order.status = 1
        order.update_time = datetime.now()
        goods.add_increase_num(order.num)

        db.session.commit()
        return restful.success()
    except Exception as e:
        print(e)
        db.session.rollback()
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


@bp.route('/pick_up_v2/', methods=['POST'])         # 提货
@login_required_query
def pick_up_v2():
    num = request.form.get('num', type=int)
    goods_id = request.form.get('goods_id', type=int)
    pick_type = request.form.get('pick_type', type=int)     # 1.资产一，2.资产二，3.提货拍品，4.可交易拍品

    sh_name = request.form.get('sh_name')
    sh_phone = request.form.get('sh_phone')
    sh_province = request.form.get('sh_province')
    sh_city = request.form.get('sh_city')
    sh_district = request.form.get('sh_district')
    sh_place = request.form.get('sh_place')

    if num <= 0:
        return restful.params_error(message='数量格式错误')
    if pick_type not in (1, 2, 3, 4):
        return restful.params_error("数据格式错误")

    goods = Goods.query.filter_by(id=goods_id, status=1).first()
    if goods is None:
        return restful.params_error("未找到商品")

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods_id)
    if pick_type == 1 and user_extend2.s_borrow_num < num:
        return restful.params_error("库存数量不足")
    elif pick_type == 2 and user_extend2.s_release_num < num:
        return restful.params_error("库存数量不足")
    elif pick_type == 3 and user_extend2.s_take_num < num:
        return restful.params_error("库存数量不足")
    elif pick_type == 4 and user_extend2.s_sell_Num < num:
        return restful.params_error("库存数量不足")

    buy_deal_deliver = BuyDealDeliver(
        num=num, price=0, total_price=0, sh_name=sh_name, sh_phone=sh_phone, sh_province=sh_province, sh_city=sh_city,
        sh_district=sh_district, sh_place=sh_place, user_id=g.user.id, goods_id=goods_id, t_type=1, pick_type=pick_type
    )
    db.session.add(buy_deal_deliver)
    db.session.flush()

    if pick_type == 1:      # 资产一
        user_extend2.s_borrow_num -= num
        api_util.user_record(g.user.id, 10, 1, 1, 1, num)

    elif pick_type == 2:    # 资产二
        user_extend2.s_release_num -= num
        api_util.user_record(g.user.id, 10, 1, 1, 1, num)

    elif pick_type == 3:    # 提货拍品
        # 扣除提货数量
        user_extend2.s_take_num -= num
        api_util.user_record(g.user.id, 10, 1, 1, 1, num)

        # 增加提货券
        user_extend2.s_coupon_num += num * 2
        api_util.user_record(g.user.id, 10, 1, 1, 1, num)
        expire_day = 7
        # expire_day = GlobalParams.get_params(12)
        expire_time = (datetime.now() + timedelta(days=int(expire_day))).strftime('%Y-%m-%d 23:59:59')
        create_coupon = MallCoupon(
            order_id=buy_deal_deliver.id, user_id=g.user.id, goods_id=goods.id,
            num=num * 2, s_num=num * 2, status=0, t_type=1, expire_time=expire_time
        )
        db.session.add(create_coupon)

    elif pick_type == 4:    # 可交易拍品
        user_extend2.s_sell_num -= num
        api_util.user_record(g.user.id, 10, 1, 1, 1, num)

    db.session.commit()
    return restful.success('提货成功')


@bp.route('/one_touch_redeposit/', methods=['POST'])      # 一键转存
@login_required_query
def one_touch_redeposit():
    goods_id = request.form.get('goods_id', type=int)

    goods = Goods.query.filter_by(id=goods_id, status=1).first()
    if goods is None:
        return restful.params_error("未找到商品")

    user_extend2 = UserExtend2.return_user_extend2(g.user.id, goods_id)
    if user_extend2.s_release_num <= 0:
        return restful.params_error("没有可转存数量")

    total_num = user_extend2.s_release_num
    user_extend2.s_release_num = 0
    user_extend2.s_borrow_num += total_num

    # 做记录

    db.session.commit()
    return restful.success()

